using BootstrapBlazor.Components;
using Identity.Models;
using Microsoft.AspNetCore.Components.Routing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WorkSystem.Client.Extensinos
{
 public static class MenuExtensions
    {    
       
       public static MenuItem Parse(this Navigation menu) => new()
       {
           Text = menu.Name,
           Url = menu.Url.Replace("~/", "/"),
           Icon = menu.Icon,
           Match = NavLinkMatch.All,
           Target = menu.Target,
           Id = menu.Id,
           ParentId = menu.ParentId
       };

       /// <summary>
       /// 获取后台管理菜单
       /// </summary>
       /// <returns></returns>
       public static IEnumerable<MenuItem> ToMenus(this IEnumerable<Navigation> navigations)
       {
           var menus = navigations.Where(m => m.Category == EnumNavigationCategory.System && m.IsResource == 0);
           return CascadeMenus(menus);
       }

       /// <summary>
       /// 获得带层次关系的菜单集合
       /// </summary>
       /// <param name="navigations">未层次化菜单集合</param>
       /// <returns>带层次化的菜单集合</returns>
       public static IEnumerable<MenuItem> CascadeMenus(IEnumerable<Navigation> navigations)
       {
           var root = navigations.Where(m => string.IsNullOrEmpty(m.ParentId))
               .OrderBy(m => m.Category).ThenBy(m => m.Application).ThenBy(m => m.Order)
               .Select(m => m.Parse())
               .ToList();
           CascadeMenus(navigations, root);
           return root;
       }

       private static void CascadeMenus(IEnumerable<Navigation> navigations, List<MenuItem> level)
       {
           level.ForEach(m =>
           {
               m.Items = navigations.Where(sub => sub.ParentId == m.Id).OrderBy(sub => sub.Order).Select(sub => sub.Parse()).ToList();
               CascadeMenus(navigations, m.Items.ToList());
           });
       }
   }

}